package nut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import nut.common.handler.exceptionhandler.MyException;
import nut.common.utils.JwtUtil;
import nut.entity.*;
import nut.entity.vo.ResumeBaseInfoVO;
import nut.entity.vo.ResumeCoreInfoVO;
import nut.entity.vo.ResumeInfoVo;
import nut.mapper.*;
import nut.service.EnterpriseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import nut.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author 郜宇博
 * @since 2021-12-19
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {
    private final EnterpriseDisplayMapper enterpriseDisplayMapper;
    private final ResumeMapper resumeMapper;
    private final EnterpriseResumeMapper enterpriseResumeMapper;
    private final ResumeBaseInfoMapper resumeBaseInfoMapper;
    private final RecruitMapper recruitMapper;
    private final UserService userService;

    public EnterpriseServiceImpl(UserService userService,RecruitMapper recruitMapper,EnterpriseDisplayMapper enterpriseDisplayMapper,ResumeMapper resumeMapper,EnterpriseResumeMapper enterpriseResumeMapper,ResumeBaseInfoMapper resumeBaseInfoMapper) {
        this.userService = userService;
        this.recruitMapper = recruitMapper;
        this.enterpriseResumeMapper = enterpriseResumeMapper;
        this.resumeBaseInfoMapper = resumeBaseInfoMapper;
        this.resumeMapper = resumeMapper;
        this.enterpriseDisplayMapper = enterpriseDisplayMapper;
    }

    @Override
    public String login(Enterprise enterpriseUser) {
        String username = enterpriseUser.getUsername();
        String password = enterpriseUser.getPassword();
        //非空校验
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new MyException(20001,"账号或密码为空");
        }
        //判断用户名是否正确
        Enterprise loginUser = baseMapper.selectOne(new QueryWrapper<Enterprise>()
                .eq("username", username));
        System.out.println(username);
        if (loginUser == null){
            throw new MyException(20001,"用户名不存在");
        }
        //判断密码
        if (!password.equals(loginUser.getPassword())){
            throw new MyException(20001,"密码错误");
        }
        //登录成功
        return JwtUtil.getJwtToken(String.valueOf(loginUser.getEid()), username);
    }

    @Override
    public void register(Enterprise enterpriseUser) {
        //获取注册数据
        String username = enterpriseUser.getUsername();
        String password = enterpriseUser.getPassword();
        String email = enterpriseUser.getEmail();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)|| StringUtils.isEmpty(email)){
            throw new MyException(20001,"注册失败，信息不完整");
        }
        //提高效率，只需要查询是否存在，不需要查出具体对象
        Integer count = baseMapper.selectCount(new QueryWrapper<Enterprise>().eq("username", username));
        if (count > 0){
            throw new MyException(20001,"用户名已经注册");
        }
        //数据添加数据库中
        Enterprise registerUser = new Enterprise();
        registerUser.setUsername(username);
        registerUser.setPassword(password);
        registerUser.setEmail(email);
        baseMapper.insert(registerUser);
    }

    @Override
    public Enterprise getUserByToken(HttpServletRequest request) {
        //根据token获取到memberId
        String userId = JwtUtil.getMemberIdByJwtToken(request);
        //查询数据库
        return baseMapper.selectById(userId);
    }
    /**
     * 添加公司基本信息
     * @param enterpriseDisplay 公司基本信息
     */
    @Override
    public void addDisplayInfo(EnterpriseDisplay enterpriseDisplay,int eid) {
        //是否存在该公司
        //提高效率，只需要查询是否存在，不需要查出具体对象
        int count = this.count(new QueryWrapper<Enterprise>().eq("eid", eid));
        if (count == 0){
            throw new MyException(20001,"公司不存在，eid错误");
        }
        String name = enterpriseDisplay.getName();
        String address = enterpriseDisplay.getAddress();
        String website = enterpriseDisplay.getWebsite();
        String telephone = enterpriseDisplay.getTelephone();
        //注册时间
        Date registrationTime = enterpriseDisplay.getRegistrationTime();
        //注册资金
        String registeredCapital = enterpriseDisplay.getRegisteredCapital();
        boolean hasEmpty;
        hasEmpty = (StringUtils.isEmpty(registrationTime)) ||(StringUtils.isEmpty(registeredCapital)) ||(StringUtils.isEmpty(name)) ||(StringUtils.isEmpty(address)) ||(StringUtils.isEmpty(website)) ||(StringUtils.isEmpty(telephone));
        //非空校验
        if (hasEmpty){
            throw new MyException(20001,"注册信息不完整");
        }else {
            enterpriseDisplay.setEid(eid);
            enterpriseDisplayMapper.insert(enterpriseDisplay);
        }
    }

    /**
     * 分页获取本公司简历
     *
     * @param page 分页信息
     * @param eid  公司id
     * @return resumeList
     */
    @Override
    public IPage<ResumeInfoVo> getResumeList(Page<ResumeInfoVo> page, int eid) {
        //是否存在该公司
        //提高效率，只需要查询是否存在，不需要查出具体对象
        int count = this.count(new QueryWrapper<Enterprise>().eq("eid", eid));
        if (count == 0){
            throw new MyException(20001,"公司不存在，eid错误");
        }
        //获取所有的resumeId
        List<EnterpriseResume> enterpriseResumeList = enterpriseResumeMapper.selectList(new QueryWrapper<EnterpriseResume>().eq("eid", eid));
        List<ResumeInfoVo> resumeList = new ArrayList<>();
        for (EnterpriseResume enterpriseResume: enterpriseResumeList){
            //获取id
            Integer resumeId = enterpriseResume.getResumeId();
            String score = userService.getResumeScore(enterpriseResume.getRecruitId(), resumeId);
            ResumeInfoVo resumeInfoVo = (ResumeInfoVo)getResumeAllInfo(resumeId).get("resumeInfo");
            resumeInfoVo.setScore(score);
            resumeList.add(resumeInfoVo);
        }
        IPage<ResumeInfoVo> resumePage = new Page<>();
        resumePage.setCurrent(page.getCurrent());
        resumePage.setRecords(resumeList);
        resumePage.setTotal(resumeList.size());
        resumePage.setSize(page.getSize());
        return resumePage;
    }

    /**
     * 获取所有简历信息
     * @param resumeId 简历id
     * @return 所有简历信息
     */
    @Override
    public Map<String,Object> getResumeAllInfo(int resumeId){
        //获取核心和基本简历信息封装到Vo中
        Resume resume = resumeMapper.selectById(resumeId);
        ResumeBaseInfo resumeBaseInfo = resumeBaseInfoMapper.selectById(resumeId);
        ResumeBaseInfoVO resumeBaseInfoVO = new ResumeBaseInfoVO();
        ResumeCoreInfoVO resumeCoreInfoVO = new ResumeCoreInfoVO();
        BeanUtils.copyProperties(resume,resumeCoreInfoVO);
        BeanUtils.copyProperties(resumeBaseInfo,resumeBaseInfoVO);
        //兼容之前返回全部简历信息、、、、、、、、、、、、、、、、、、、、
        ResumeInfoVo resumeInfoVo = new ResumeInfoVo();
        BeanUtils.copyProperties(resume,resumeInfoVo);
        BeanUtils.copyProperties(resumeBaseInfo,resumeInfoVo);
        resumeInfoVo.setUpdateTime(resumeBaseInfo.getGmtModified());
        resumeBaseInfoVO.setUpdateTime(resumeBaseInfo.getGmtModified());
        resumeCoreInfoVO.setUpdateTime(resume.getGmtModified());
        HashMap<String, Object> map = new HashMap<>(5);
        map.put("resumeBaseInfo",resumeBaseInfoVO);
        map.put("resumeCoreInfo",resumeCoreInfoVO);
        map.put("resumeInfo",resumeInfoVo);
        return map;
    }

    /**
     * 获取公司基本信息
     *
     * @param eid 企业id
     * @return 企业id
     */
    @Override
    public EnterpriseDisplay getDisplayInfo(int eid) {
        if (StringUtils.isEmpty(eid)){
            throw new MyException(20001,"企业id为null");
        }
        //查询展示信息
        return enterpriseDisplayMapper.selectById(eid);
    }
    /**
     * 根据eid获取所有招聘
     * @param eid eid
     * @return Recruits
     */
    @Override
    public List<Recruit> getRecruitsByEid(int eid){
        if (StringUtils.isEmpty(eid)){
            throw new MyException(20001,"企业id为null");
        }
        return recruitMapper.selectList(new QueryWrapper<Recruit>().eq("eid", eid));
    }
}
